<template>
  <div>
    <template v-if="!hiddenInput">
      <template v-if="select_num > 1">
        <a-button @click="onClickUploadBtn" :size="size" :type="buttonType">
          {{ buttonText }}
        </a-button>
      </template>
      <template v-else>
        <a-input
          :placeholder="placeholder"
          :disabled="disabled"
          :size="size"
          v-model="select_value"
        >
          <a-popover slot="addonBefore" v-if="type === 'image'">
            <template slot="content">
              <img
                class="preview-img"
                :src="select_value"
                v-if="select_value"
              />
              <p v-else>暂未选择图片</p>
            </template>
            <a-icon class="cursor-pointer" type="file-image" />
          </a-popover>
          <a-tooltip
            @click="onClickPreview(select_value)"
            slot="addonBefore"
            title="点击预览"
            v-if="type === 'video'"
          >
            <a-icon class="cursor-pointer" type="video-camera" />
          </a-tooltip>
          <a-tooltip
            :title="'上传/选择资源' + showSizeTips"
            slot="addonAfter"
            @click="onClickUploadBtn"
            v-if="operation"
          >
            <a-icon class="cursor-pointer" type="cloud-upload" />
          </a-tooltip>
        </a-input>
      </template>
    </template>
    <!-- 选择图片 -->
    <a-modal
      :title="title"
      :visible="storage_modal"
      :keyboard="false"
      :maskClosable="false"
      width="900px"
      @ok="onOk"
      @cancel="onCancel"
    >
      <div class="header">
        <a-row :gutter="[10, 10]">
          <a-col :span="24">
            <a-button-group>
              <a-button @click="onClickAddNewDir"
                ><a-icon type="plus-circle" />新增目录</a-button
              >
              <a-button type="primary" @click="upload_modal = true"
                ><a-icon type="cloud-upload" />上传资源</a-button
              >
            </a-button-group>

            <a-button-group style="margin-left: 20px;">
              <a-tooltip title="勾选全部资源">
                <a-button @click="onClickAllCheck"
                  ><a-icon type="check-square" />全选</a-button
                >
              </a-tooltip>
              <a-tooltip title="反向勾选资源">
                <a-button @click="onClickReverseCheck"
                  ><a-icon type="border" />反选</a-button
                >
              </a-tooltip>
              <a-tooltip
                :title="'清除已选' + this.list_checked.length + '个资源'"
              >
                <a-button @click="onClickClean"
                  ><a-icon type="reload" />
                  清除
                  <template v-if="this.list_checked.length > 0"
                    >({{ this.list_checked.length }})</template
                  >
                </a-button>
              </a-tooltip>
            </a-button-group>

            <a-button-group style="margin-left: 20px;">
              <a-button @click="onClickDrag"
                ><a-icon type="drag" />移动</a-button
              >
              <a-button @click="onClickMultiDelete"
                ><a-icon type="delete" />删除</a-button
              >
            </a-button-group>
          </a-col>
        </a-row>
        <a-row :gutter="[10, 10]">
          <a-col :span="24">
            <a-select
              default-value="id"
              style="width: 120px"
              @change="onSortTypeChange"
            >
              <a-select-option value="id">
                编号
              </a-select-option>
              <a-select-option value="name">
                名称
              </a-select-option>
              <a-select-option value="ext">
                扩展名
              </a-select-option>
              <a-select-option value="created_at">
                创建时间
              </a-select-option>
              <a-select-option value="updated_at">
                更新时间
              </a-select-option>
            </a-select>
            <a-select
              default-value="降序"
              style="width: 120px;margin-left: 20px;"
              @change="onSortMethodChange"
            >
              <a-select-option value="asc">
                升序
              </a-select-option>
              <a-select-option value="desc">
                降序
              </a-select-option>
            </a-select>
            <a-input-group
              compact
              style="display: inline-block;width: 350px;margin-left: 20px;top: -5px;"
            >
              <a-input
                v-model.trim="search_name"
                style="width: 268px"
                allowClear
                placeholder="搜索资源名称"
              ></a-input>
              <a-button type="primary" @click="onSearch">
                <a-icon type="search" />搜索
              </a-button>
            </a-input-group>
            <a-button @click="onResetSearch" style="margin-left: 20px;">
              <a-icon type="reload" />重置
            </a-button>
          </a-col>
        </a-row>
      </div>
      <div class="breadcrumb">
        <template v-if="is_search">
          搜索结果
        </template>
        <template v-else>
          <div
            class="breadcrumb-item cursor-pointer"
            v-for="(item, index) of showBreadcrumb"
            @click="onClickBreadcrumb(item)"
            :key="index"
          >
            {{ item.name }}
          </div>
        </template>
      </div>
      <div style="min-height: 100px;max-height: 500px;overflow: hidden auto">
        <a-list
          style="margin-top: 1px;margin-left: 1px;"
          :grid="{ column: 8 }"
          :data-source="list"
          :loading="list_loading"
        >
          <div style="width: 100%;height: 100px;" v-if="list_loading"></div>
          <template v-if="list.length > 0">
            <div
              v-if="show_loading_more"
              slot="loadMore"
              :style="{
                textAlign: 'center',
                marginTop: '12px',
                height: '32px',
                lineHeight: '32px',
              }"
            >
              <a-spin v-if="loading_more" />
              <a-button v-else @click="onLoadMore">
                加载更多
              </a-button>
            </div>
          </template>
          <a-list-item slot="renderItem" slot-scope="item">
            <div class="list-item">
              <div
                class="list-item-checked"
                @click="onClickCheck(item)"
                v-if="list_checked_ids.indexOf(item.id) > -1"
              >
                <a-icon type="check" style="color: #fff;font-size: 30px" />
              </div>
              <div
                class="list-item-img"
                @click="onClickCheck(item)"
                v-if="item.type === type_image"
                :style="{ backgroundImage: 'url(' + item.url + ')' }"
              ></div>
              <div
                class="list-item-img"
                @dblclick="onClickDir(item)"
                v-if="item.type === type_dir"
                :style="{ backgroundImage: 'url(' + dirPng + ')' }"
              ></div>
              <div
                class="list-item-img"
                @click="onClickCheck(item)"
                v-if="item.type === type_video"
                :style="{ backgroundImage: 'url(' + videoPng + ')' }"
              ></div>
              <a-tooltip>
                <template slot="title">
                  名称：{{ item.name }}<br />
                  日期：{{ item.updated_at | timeFormat }}
                </template>
                <div class="list-item-name">{{ item.name }}</div>
              </a-tooltip>
              <a-dropdown>
                <a-icon type="more" class="list-item-edit" />
                <a-menu slot="overlay">
                  <a-menu-item @click="onRename(item)"
                    ><a-icon type="edit" />重命名</a-menu-item
                  >
                  <a-menu-divider />
                  <a-menu-item @click="onClickDragDir(item)"
                    ><a-icon type="drag" />移动目录</a-menu-item
                  >
                  <template v-if="item.type === type_dir">
                    <a-menu-item @click="onClickDeleteDir(item)"
                      ><a-icon type="delete" />删除目录</a-menu-item
                    >
                  </template>
                  <template v-else>
                    <a-menu-item @click="onClickDeleteRes(item)"
                      ><a-icon type="delete" />删除资源</a-menu-item
                    >
                  </template>
                  <template v-if="item.type != type_dir">
                    <a-menu-divider />
                    <a-menu-item @click="onCopyLink(item)"
                      ><a-icon type="copy" />复制外链</a-menu-item
                    >
                  </template>
                </a-menu>
              </a-dropdown>
            </div>
          </a-list-item>
        </a-list>
      </div>
      <!-- 已选列表 -->
      <template v-if="list_checked.length > 0">
        <a-divider>已选资源 ( {{ list_checked.length }} )</a-divider>
        <div class="checked-list">
          <div
            class="checked-list-item"
            v-for="(item, index) of list_checked"
            :key="index"
          >
            <a-icon
              type="close-circle"
              @click="onClickCloseRes(item)"
              class="checked-list-item-close"
            />
            <div
              v-if="item.type === type_image"
              class="checked-list-item-img"
              @click="onClickRes(item)"
              :style="{ backgroundImage: 'url(' + item.url + ')' }"
            ></div>
            <div
              v-if="item.type === type_video"
              class="checked-list-item-img"
              @click="onClickRes(item)"
              :style="{ backgroundImage: 'url(' + videoPng + ')' }"
            ></div>
          </div>
        </div>
      </template>
      <!-- 已选列表 end -->
    </a-modal>
    <!-- 选择图片 end -->
    <!-- 上传资源 -->
    <a-modal
      title="上传资源"
      :visible="upload_modal"
      :keyboard="false"
      :maskClosable="false"
      width="500px"
      @cancel="onUploadCancel"
      :footer="null"
    >
      <a-upload-dragger
        :accept="upload_file_mime"
        :action="upload_url"
        :data="{ parent_id, store_id }"
        :headers="upload_headers"
        :listType="upload_list_style"
        :multiple="true"
        :name="upload_file_name"
        :remove="onUploadRemove"
        :fileList="fileList"
        @change="onUploadChange"
        @reject="onUploadReject"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          点击或拖拽文件到此区域上传
        </p>
        <p class="ant-upload-hint">
          支持多文件上传，单文件大小限制：{{ option.max_upload_size }}M<br />
          支持上传的文件扩展名：{{ upload_file_ext }}
        </p>
      </a-upload-dragger>
    </a-modal>
    <!-- 上传资源 end -->
    <!-- 新增目录 -->
    <a-modal
      :title="new_dir_title"
      :visible="new_dir_modal"
      :keyboard="false"
      :maskClosable="false"
      width="500px"
      :confirm-loading="confirm_loading"
      @ok="onNewDirOk"
      @cancel="onNewDirCancel"
    >
      <a-input v-model="new_dir_name" placeholder="请输入目录名称" />
    </a-modal>
    <!-- 新增目录 end -->
    <!-- 移动目录 -->
    <a-modal
      title="移动目录"
      :visible="drag_dir_modal"
      :keyboard="false"
      :maskClosable="false"
      width="500px"
      :confirm-loading="drag_confirm_loading"
      @ok="onDragDirOk"
      @cancel="onDragDirCancel"
    >
      <div
        v-if="drag_loading"
        :style="{
          textAlign: 'center',
          marginTop: '12px',
          height: '32px',
          lineHeight: '32px',
        }"
      >
        <a-spin />
      </div>
      <template v-else>
        <a-tree
          :tree-data="dir_tree_data"
          :default-expanded-keys="['0']"
          @select="onDirTreeSelete"
        >
        </a-tree>
      </template>
    </a-modal>
    <!-- 移动目录 end -->
  </div>
</template>

<script>
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import api, {
  getOption,
  addDir,
  getList,
  rename,
  deleteRes,
  deleteDir,
  getDirTree,
  dragDir,
} from "@/api/storage";
import dirPng from "@/assets/images/diy/dir.png";
import videoPng from "@/assets/images/diy/video.png";
import Template from "./Template.vue";
import { mapActions } from "vuex";
import { uniqueId } from "lodash";

import { getAuthorization, getUrlParam } from "@/utils/utils";


export default {
  components: { Template },
  name: "StorageSelect",
  data() {
    return {
      auto_id: uniqueId(),
      dirPng: dirPng,
      videoPng: videoPng,
      option: {},
      upload_modal: false,
      new_dir_modal: false,
      drag_dir_modal: false,
      parent_id: 0, // 父级id
      store_id: 1, // store_id
      new_dir_title: "新建目录",
      new_dir_name: "", // 新建/编辑文件夹名称
      confirm_loading: false,
      drag_loading: false,
      drag_confirm_loading: false,
      upload_file_mime: "",
      upload_file_ext: "",
      list: [], // 数据列表
      breadcrumb: [], // 面包屑列表
      list_loading: false,
      show_loading_more: true,
      loading_more: false,
      page: 1, // 分页
      list_total: 0, // 数据总数
      sort_type: "id",
      sort_method: "desc",
      search_name: "",
      type_dir: "2",
      type_image: "0",
      type_video: "1",
      current_item: null, // 当前操作文件或目录
      is_search: false,
      list_checked: [],
      dir_tree_data: [], // 目录树
      selected_dir_tree_key: null, // 选中的目录树id
      select_value: "",
      fileList: [],
    };
  },
  model: {
    prop: "defaultValue",
    event: "input",
  },
  props: {
    // 隐藏input框，用于某些情况下单独弹出图片选择框
    hiddenInput: {
      type: Boolean,
      default: false,
    },
    // 按钮或input大小,可选值small,default,large
    size: {
      type: String,
      default: "default",
    },
    // 资源类型，image图片,video视频
    type: {
      type: String,
      default: "image",
    },
    // 需要选择资源数量，1个资源展示Input框，>1则显示按钮
    selectNum: {
      type: [Number, String],
      default: () => {
        return 1;
      },
    },
    // 输入框默认值，编辑的时候有用，只针对获取1个资源数量有用
    defaultValue: {
      type: String,
      default: "",
    },
    // 按钮文字
    buttonText: {
      type: String,
      default: "选择资源",
    },
    // 按钮样式, 可选值primary, dashed, danger, link, default
    buttonType: {
      type: String,
      default: "default",
    },
    // Input框placeholder属性
    placeholder: {
      type: String,
      default: "",
    },
    // 可操作 or 不可操作
    operation: {
      type: Boolean,
      default: true,
    },
    // 推荐尺寸提醒
    sizeTips: {
      type: String,
      default: "",
    },
    // 自定义id, 如果传入此值, 优先使用, 否则自动生成
    id: {
      type: [Number, String],
      default: 0,
    },
    // input框是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    if (getUrlParam("store_id")) this.store_id = getUrlParam("store_id");
    this.select_value = this.defaultValue;
  },
  computed: {
    current_id: function() {
      return this.id !== 0 ? this.id : this.auto_id;
    },
    title: function() {
      return this.type === "image" ? "选择图片" : "选择视频";
    },
    upload_url: function() {
      const baseUrl = this.$envCnfig.baseUrl;
      return this.type === "image"
        ? baseUrl + api.upload_images
        : baseUrl + api.upload_videos;
    },
    upload_list_style: function() {
      return this.type === "image" ? "picture" : "text";
    },
    upload_file_name: function() {
      return this.type === "image" ? "images" : "videos";
    },
    upload_headers: function() {
      // const token = storage.get(ACCESS_TOKEN);
      const token = getAuthorization();
      return { Authorization: "Bearer " + token };
    },
    showBreadcrumb: function() {
      const breadcrumb = this.breadcrumb;
      if (breadcrumb.length === 0) {
        breadcrumb.unshift({
          id: "0",
          name: "根目录",
        });
      }
      return breadcrumb;
    },
    list_checked_ids: function() {
      const listChecked = [];
      for (let i = 0; i < this.list_checked.length; i++) {
        listChecked.push(this.list_checked[i].id);
      }
      return listChecked;
    },
    select_num: function() {
      return parseInt(this.selectNum);
    },
    showSizeTips: function() {
      return this.sizeTips ? " , 推荐尺寸" + this.sizeTips : "";
    },
    storage_modal: function() {
      return this.$store.getters.storage_modal[this.current_id];
    },
  },
  watch: {
    storage_modal: function(val) {
      if (val) {
        getOption().then((res) => {
          if (res.code === 0) {
            this.option = res.data;
            const fileMime =
              this.type === "image"
                ? this.option.image_mime
                : this.option.video_mime;
            this.upload_file_mime = fileMime.join(", ");
            const fileExt =
              this.type === "image"
                ? this.option.image_type
                : this.option.video_type;
            this.upload_file_ext = fileExt.join(", ");
          }
        });
        this.current_item = null;
        this.is_search = false;
        this.search_name = "";
        this.list_checked = [];
        this.sort_type = "id";
        this.sort_method = "desc";
        this.breadcrumb = [];
        this.parent_id = 0;
        this.resetData();
      }
    },
    drag_dir_modal: function(val) {
      if (val) {
        this.selected_dir_tree_key = null;
      }
    },
    select_value: function(val) {
      console.log(val, "214");
      this.$emit("input", val);
    },
  },
  methods: {
    ...mapActions(["showStorageSelect", "hiddenStorageSelect"]),
    onLoadMore: function() {
      this.onLoadData(true);
    },
    resetData: function() {
      this.page = 1;
      this.list = [];
      this.list_total = 0;
      this.show_loading_more = true;
      this.onLoadData();
    },
    // 加载数据
    onLoadData: function(clickButton = false) {
      if (clickButton) {
        this.loading_more = true;
      } else {
        this.list_loading = true;
      }

      getList({
        pageNo: this.page,
        pageSize: 48,
        parent_id: this.parent_id,
        sort_type: this.sort_type,
        sort_method: this.sort_method,
        search_name: this.search_name,
        type: this.type === "image" ? this.type_image : this.type_video,
      })
        .then((res) => {
          if (res.code === 0) {
            this.list = this.list.concat(res.data.list);
            this.list_total = res.data.totalCount;
            if (this.list.length < this.list_total) {
              this.page++;
            } else {
              this.show_loading_more = false;
            }
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .then(() => {
          if (clickButton) {
            this.loading_more = false;
          } else {
            this.list_loading = false;
          }
        });
    },
    // 点击确定按钮
    onOk: function() {
      if (this.list_checked.length > 0) {
        if (this.select_num === 1) {
          this.select_value = this.list_checked[0].url;
          this.$emit("onOk", this.list_checked[0].url);
        } else {
          const values = [];
          for (let i = 0; i < this.select_num; i++) {
            if (!this.list_checked[i]) {
              break;
            }
            values.push(this.list_checked[i].url);
          }
          this.$emit("onOk", values);
        }
      }

      this.hiddenStorageSelect(this.current_id);
    },
    // 点击取消按钮
    onCancel: function() {
      this.hiddenStorageSelect(this.current_id);
    },
    // 点击选择资源按钮
    onClickUploadBtn: function() {
      this.showStorageSelect(this.current_id);
    },
    // 搜索
    onSearch: function() {
      this.is_search = this.search_name !== "";
      this.resetData();
    },
    // 重置搜索
    onResetSearch: function() {
      this.search_name = "";
      this.is_search = false;
      this.resetData();
    },
    // 排序类型
    onSortTypeChange: function(val) {
      if (this.sort_type === val) {
        return;
      }
      this.sort_type = val;
      this.resetData();
    },
    // 排序方法
    onSortMethodChange: function(val) {
      if (this.sort_method === val) {
        return;
      }
      this.sort_method = val;
      this.resetData();
    },
    // 上传资源取消按钮
    onUploadCancel: function() {
      this.upload_modal = false;
      if (this.fileList.length > 0) {
        this.resetData();
        this.fileList = [];
      }
    },
    // 点击新增目录按钮
    onClickAddNewDir: function() {
      this.new_dir_title = "新增目录";
      this.new_dir_name = "";
      this.current_item = null;
      this.new_dir_modal = true;
    },
    // 新增或编辑目录确定按钮
    onNewDirOk: function() {
      const dirName = this.new_dir_name.trim();
      if (dirName === "") {
        if (
          this.new_dir_title === "新增目录" ||
          (this.current_item && this.current_item.type === this.type_dir)
        ) {
          this.$message.warning("请输入目录名称");
        } else {
          this.$message.warning("请输入资源名称");
        }
        return;
      }
      this.confirm_loading = true;
      if (this.current_item) {
        rename({
          id: this.current_item.id,
          name: dirName,
        })
          .then((res) => {
            if (res.code === 0) {
              this.new_dir_modal = false;
              this.$message.success(res.msg);
              this.current_item = null;
              this.resetData();
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((error) => {
            console.log(error);
          })
          .then(() => {
            this.confirm_loading = false;
          });
      } else {
        addDir({
          dir_name: this.new_dir_name,
          parent_id: this.parent_id,
        })
          .then((res) => {
            if (res.code === 0) {
              this.new_dir_modal = false;
              this.$message.success(res.msg);
              this.resetData();
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((error) => {
            console.log(error);
          })
          .then(() => {
            this.confirm_loading = false;
          });
      }
    },
    // 新增目录取消按钮
    onNewDirCancel: function() {
      this.new_dir_name = "";
      this.current_item = null;
      this.new_dir_modal = false;
    },
    // 上传文件删除回调
    onUploadRemove: function() {
      //
    },
    // 上传文件改变事件
    onUploadChange: function(info) {
      const mime =
        this.type === "image" ? this.option.image_mime : this.option.video_mime;
      const list = [];
      for (let i = 0; i < info.fileList.length; i++) {
        if (mime.indexOf(info.fileList[i].type) === -1) {
          this.$message.warning(
            "文件 " + info.fileList[i].name + " 格式不支持上传"
          );
        } else {
          list.push(info.fileList[i]);
        }
      }
      this.fileList = list;
    },
    // 拖动上传文件不符合accept类型
    onUploadReject: function(fileList) {
      const mime =
        this.type === "image" ? this.option.image_mime : this.option.video_mime;
      for (let i = 0; i < fileList.length; i++) {
        if (mime.indexOf(fileList[i].type) === -1) {
          this.$message.warning("文件 " + fileList[i].name + " 格式不支持上传");
        }
      }
    },
    // 点击面包屑
    onClickBreadcrumb: function(item) {
      if (this.parent_id === item.id) {
        return;
      }
      this.parent_id = item.id;
      const breadcrumb = this.breadcrumb;
      const newBreadcrumb = [];
      for (let i = 0; i < breadcrumb.length; i++) {
        newBreadcrumb.push(breadcrumb[i]);
        if (breadcrumb[i].id === item.id) {
          break;
        }
      }
      this.breadcrumb = newBreadcrumb;
      this.resetData();
    },
    // 重命名
    onRename: function(item) {
      this.current_item = item;
      if (item.type === this.type_dir) {
        this.new_dir_title = "重命名目录";
      } else {
        this.new_dir_title = "重命名资源";
      }
      this.new_dir_name = item.name;
      this.new_dir_modal = true;
    },
    onCopyLink: function(item) {
      this.$copyText(item.url)
        .then((e) => {
          this.$message.success("复制成功");
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("复制失败");
        });
    },
    // 点击目录
    onClickDir: function(item) {
      this.breadcrumb.push(item);
      this.parent_id = item.id;
      this.resetData();
    },
    // 点击选中/取消选中
    onClickCheck: function(item) {
      const index = this.list_checked.findIndex((value) => {
        return value.id === item.id;
      });
      if (index > -1) {
        this.list_checked.splice(index, 1);
      } else {
        this.list_checked.push(item);
      }
    },
    // 点击全选
    onClickAllCheck: function() {
      const checked = [];
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].type !== this.type_dir) {
          checked.push(this.list[i]);
        }
      }
      this.list_checked = checked;
    },
    // 点击清除
    onClickClean: function() {
      this.list_checked = [];
    },
    // 点击反选
    onClickReverseCheck: function() {
      const listChecked = this.list_checked;
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].type !== this.type_dir) {
          const index = this.list_checked_ids.indexOf(this.list[i].id);
          if (index > -1) {
            listChecked.splice(index, 1);
          } else {
            listChecked.push(this.list[i]);
          }
        }
      }
      this.list_checked = listChecked;
    },
    // 点击顶部删除按钮
    onClickMultiDelete: function() {
      if (this.list_checked.length === 0) {
        this.$message.warning("请选择要删除的资源");
        return;
      }
      this.$confirm({
        content: "确定要删除选中的资源吗?",
        onOk: () => {
          return new Promise((resolve, reject) => {
            deleteRes({
              ids: this.list_checked_ids,
            })
              .then((res) => {
                resolve();
                if (res.code === 0) {
                  this.list_checked = [];
                  this.$message.success("删除成功");
                  this.resetData();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((error) => {
                console.log(error);
                reject(error);
              });
          });
        },
      });
    },
    // 删除目录
    onClickDeleteDir: function(item) {
      this.$confirm({
        content: "确定要删除该目录吗? (该目录下级子目录都会被删除)",
        onOk: () => {
          return new Promise((resolve, reject) => {
            deleteDir({
              id: item.id,
            })
              .then((res) => {
                resolve();
                if (res.code === 0) {
                  this.$message.success("删除成功");
                  this.resetData();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((error) => {
                console.log(error);
                reject(error);
              });
          });
        },
      });
    },
    // 删除资源
    onClickDeleteRes: function(item) {
      this.$confirm({
        content: "确定要删除该资源吗?",
        onOk: () => {
          return new Promise((resolve, reject) => {
            deleteRes({
              ids: [item.id],
            })
              .then((res) => {
                resolve();
                if (res.code === 0) {
                  this.$message.success("删除成功");
                  this.resetData();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((error) => {
                console.log(error);
                reject(error);
              });
          });
        },
      });
    },
    // 点击顶部移动按钮
    onClickDrag: function() {
      if (this.list_checked.length === 0) {
        this.$message.warning("请选择要移动的资源");
        return;
      }
      this.drag_dir_modal = true;
      this.getDirTreeData();
    },
    // 点击移动目录弹窗取消按钮
    onDragDirCancel: function() {
      this.drag_dir_modal = false;
    },
    // 点击移动目录弹窗确定按钮
    onDragDirOk: function() {
      if (this.selected_dir_tree_key === null) {
        this.$message.warning("请选择要移动到的目录");
        return;
      }
      this.drag_confirm_loading = true;
      dragDir({
        parent_id: this.selected_dir_tree_key,
        ids: this.current_item ? this.current_item.id : this.list_checked_ids,
      })
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("移动成功");
            this.drag_dir_modal = false;
            this.list_checked = [];
            this.current_item = null;
            this.resetData();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .then(() => {
          this.drag_confirm_loading = false;
        });
    },
    // 获取目录树
    getDirTreeData: function(exclude_id = null) {
      this.drag_loading = true;
      getDirTree({
        exclude_id: exclude_id,
      })
        .then((res) => {
          if (res.code === 0) {
            this.dir_tree_data = res.data;
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .then(() => {
          this.drag_loading = false;
        });
    },
    // 选中目录树
    onDirTreeSelete: function(selectedKeys) {
      this.selected_dir_tree_key = selectedKeys[0] ? selectedKeys[0] : null;
    },
    // 点击移动单个资源或目录
    onClickDragDir: function(item) {
      this.current_item = item;
      this.drag_dir_modal = true;
      if (item.type === this.type_dir) {
        this.getDirTreeData(item.id);
      } else {
        this.getDirTreeData();
      }
    },
    // 点击已选资源
    onClickRes: function(item) {
      window.open(item.url);
    },
    // 删除已选资源
    onClickCloseRes: function(item) {
      const index = this.list_checked.findIndex((value) => {
        return value.id === item.id;
      });
      if (index > -1) {
        this.list_checked.splice(index, 1);
      }
    },
    // 预览视频
    onClickPreview: function(url) {
      if (!url) {
        this.$message.warning("没有资源可以预览");
        return;
      }
      window.open(url);
    },
  },
};
</script>
<style>
.ant-list-grid .ant-col > .ant-list-item {
  margin-bottom: 0;
}
</style>
<style scoped>
.cursor-pointer {
  cursor: pointer;
}
.breadcrumb {
  margin-top: 20px;
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 2px;
  padding: 5px 10px;
}
.breadcrumb-item {
  position: relative;
  display: inline-block;
  padding-right: 21px;
}
.breadcrumb-item::after {
  position: absolute;
  content: "/";
  display: inline-block;
  color: #ddd;
  padding: 0 8px;
}
.breadcrumb-item:last-child {
  padding-right: 0;
}
.breadcrumb-item:last-child::after {
  display: none;
}
.list-item {
  border: 1px solid #eee;
  margin-left: -1px;
  margin-top: -1px;
  padding: 10px 10px 0 10px;
  position: relative;
}
.list-item-img {
  width: 100%;
  height: 80px;
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
}
.list-item-name {
  text-align: center;
  padding: 5px 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.list-item-edit {
  cursor: pointer;
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: none;
}
.list-item:hover .list-item-edit {
  display: block;
}
.list-item-checked {
  position: absolute;
  width: 100%;
  height: 90px;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
.checked-list {
  width: 100%;
  padding-bottom: 20px;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
}
.checked-list-item {
  display: inline-block;
  position: relative;
  margin-right: 15px;
  margin-bottom: 5px;
}
.checked-list-item-img {
  width: 80px;
  height: 80px;
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
  cursor: pointer;
}
.checked-list-item:last-child {
  margin-right: 0;
}
.checked-list-item-close {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: -25px;
  font-size: 20px;
  cursor: pointer;
}
.preview-img {
  width: 200px;
  height: auto;
  display: block;
}
</style>
